package com.zb.netty.chat.server.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zb.netty.chat.client.ChatClient;
import com.zb.netty.chat.server.session.SessionFactory;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@ChannelHandler.Sharable
public class QuitHandler extends ChannelInboundHandlerAdapter {
    static final Logger log = LoggerFactory.getLogger(ChatClient.class);

    // 当连接断开时触发 inactive 事件
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("{} 已经断开", ctx.channel());
        SessionFactory.getSession().unbind(ctx.channel());
    }

    // 当出现异常时触发
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("{} 已经异常断开 异常是{}", ctx.channel(), cause.getMessage());
        SessionFactory.getSession().unbind(ctx.channel());
    }
}
